//
//  DoctorIntroduceController.m
//  HarmonizePub
//
//  Created by rzhy on 2016/11/8.
//  Copyright © 2016年 Zy. All rights reserved.
//

#import "DoctorIntroduceController.h"
#import <YYModel.h>
#import <UINavigationController+FDFullscreenPopGesture.h>
#import "Config.h"
#import "DoctorIntrTableView.h"
#import "DoctIntrHeadView.h"
#import "ScheduleDoctor.h"
#import "ChoosePatientViewController.h"
#import "NoCardAppointmentViewViewController.h"
#import "RegisterDoctorController.h"
#import "SchedulingController.h"

#define labelFont [UIFont systemFontOfSize:13.0f]

@interface DoctorIntroduceController () <UIScrollViewDelegate, UITableViewDelegate, UITableViewDataSource>
{
    CGRect _frame;
    UITableView *_intrTableView;
    DoctorIntrTableView *_scheduleTableView;
    NSDictionary *_dataDict;
    NSArray *_headTitleArray;
    
}
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *depNameLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *depLabelLayoutConstraint;
@property (weak, nonatomic) IBOutlet UILabel *jobLabel;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *jobLabelLayoutConstraint;
@property (weak, nonatomic) IBOutlet UIView *dockView;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

@implementation DoctorIntroduceController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    self.title = @"专家介绍";
    _headTitleArray = @[@{@"image" : @"Disease.png", @"title" : @"擅长疾病"}, @{@"image" : @"Introduce.png", @"title" : @"医生简介"}];
    [self getDocInfo];
    [self createTableView];
    
    _frame = self.lineView.frame;
    _frame.origin.x = (XHScreenWidth / 2 - _frame.size.width) / 2;
    _lineView.frame = _frame;
    for (UIButton *button in self.dockView.subviews)
        if ([button isKindOfClass:[UIButton class]])
            if (button.tag == _selectIndex)
                [self switchShowView:button];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.imageView.layer.cornerRadius = self.imageView.frame.size.width / 2;
    self.imageView.layer.masksToBounds = YES;
    _intrTableView.frame = (CGRect){CGPointZero, self.scrollView.frame.size};
    _scheduleTableView.frame = (CGRect){self.scrollView.frame.size.width, 0, self.scrollView.frame.size};
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)getDocInfo {
    NSString *ksdm = self.ksdm == nil ? @"" : self.ksdm;
    NSDictionary *param = @{@"ksdm" : ksdm, @"ygdm" : self.ygdm};
    NSDictionary *cookie = @{CookieVaule : [UserDefaultsTool stringForKey:XHToken]};
    __weak typeof(self) weakSelf = self;
    [HTTPSTool POSTRequestWithPath:XHGetDocInfo cookie:cookie params:param success:^(NSDictionary * _Nonnull JSON) {
        LRLog(@"获取医生详情： %@", JSON)
        _dataDict = JSON[@"data"][@"doc"];
        [weakSelf setViewAttrWithDataDictionary:_dataDict];
        _scheduleTableView.dataArray = _dataDict[@"pbList"];
        [_intrTableView reloadData];
    }];
}

- (void)setViewAttrWithDataDictionary:(NSDictionary *)dataDict {
    self.depNameLabel.text = dataDict[@"ksmc"];
    self.depLabelLayoutConstraint.constant = [self.depNameLabel.text sizeWithAttributes:@{NSFontAttributeName : self.depNameLabel.font}].width;
    self.nameLabel.text = dataDict[@"ygxm"];
    // TODO: 职位
    self.jobLabel.text = @"";
    self.jobLabelLayoutConstraint.constant = [self.jobLabel.text sizeWithAttributes:@{NSFontAttributeName : self.jobLabel.font}].width;
    NSString *imageString = dataDict[@"image"];
    self.imageView.contentMode = UIViewContentModeScaleAspectFill;
    [self.imageView downloadImageWithURLString:imageString placeholderString:@"UserIcon.png"];
}

- (void)createTableView {
    _intrTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _intrTableView.delegate = self;
    _intrTableView.dataSource = self;
    _intrTableView.contentInset = UIEdgeInsetsMake(10.0f, 0, 0, 0);
    [self.scrollView addSubview:_intrTableView];
    
    // 排班界面， 选择预约
    __weak typeof(self) weakSelf = self;
    _scheduleTableView = [[DoctorIntrTableView alloc] initWithTouchItemAction:^(NSDictionary *dataDict) {
        
        RegisterDoctorController *registerDoctor = [[RegisterDoctorController alloc] init];
        registerDoctor.selectDay = dataDict[@"pblsh"];
        //        registerDoctor.maxDay = _maxDay;
        registerDoctor.depName = dataDict[@"ksmc"];
        registerDoctor.dataDict = dataDict;
        [weakSelf.navigationController pushViewController:registerDoctor animated:YES];

    }];
    _scheduleTableView.type = self.ksdm == nil;
    [self.scrollView addSubview:_scheduleTableView];
    self.scrollView.contentSize = CGSizeMake(XHScreenWidth * 2, 0.0);
    if (@available(iOS 11.0, *)) {
        LRLog(@"安全区域safe%@ con%@ adjust%@", NSStringFromUIEdgeInsets(_scheduleTableView.safeAreaInsets), NSStringFromUIEdgeInsets(_scheduleTableView.contentInset), NSStringFromUIEdgeInsets(_scheduleTableView.adjustedContentInset));
    }
    
    
    
}

#pragma mark - tableView delegate/dataSource Method
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *text = @"暂无";
    if (indexPath.section) text = _dataDict[@"description"];
    return [text boundingRectWithSize:CGSizeMake(XHScreenWidth - 56, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName : labelFont} context:nil].size.height + 10.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.textLabel.font = labelFont;
        cell.textLabel.numberOfLines = 0;
    }
    NSString *text = @"暂无";
    if (indexPath.section) text = _dataDict[@"description"];
    cell.textLabel.text = text;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return [DoctIntrHeadView height];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section) return 0.01f;
    return 10.0f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [DoctIntrHeadView headViewWithImage:_headTitleArray[section][@"image"] title:_headTitleArray[section][@"title"]];
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
    return NO;
}


#pragma mark - 医生简介/排班情况
- (IBAction)switchShowView:(UIButton *)sender {
    for (UIButton *button in self.dockView.subviews)
        if ([button isKindOfClass:[UIButton class]])
            if (!button.enabled)
                button.enabled = YES;
    sender.enabled = NO;
    [self.scrollView setContentOffset:CGPointMake(sender.tag * XHScreenWidth, 0.0) animated:YES];
}

#pragma mark - scrollView delegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat screenWidth_2 = XHScreenWidth * 0.5;
    CGFloat moveX = scrollView.contentOffset.x / XHScreenWidth * screenWidth_2;
    static CGFloat newx = 0;
    static CGFloat oldx = 0;
    newx = scrollView.contentOffset.x;
    if (newx != oldx ) {
        CGRect rect = self.lineView.frame;
        if (newx > oldx)
            // left to right
            rect.origin.x = moveX + _frame.origin.x;
        else
            // right to left
            rect.origin.x = _frame.origin.x + screenWidth_2 - moveX;
        self.lineView.frame = rect;
    }
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self adjustmentLineViewWithScrollView:scrollView];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self adjustmentLineViewWithScrollView:scrollView];
}

- (void)adjustmentLineViewWithScrollView:(UIScrollView *)scrollView {
    NSInteger tag = scrollView.contentOffset.x / XHScreenWidth;
    for (UIButton *button in self.dockView.subviews)
        if ([button isKindOfClass:[UIButton class]])
            if (button.tag == tag) {
                [self switchShowView:button];
                CGFloat width = XHScreenWidth / 2;
                [UIView animateWithDuration:0.1f animations:^{
                    CGRect rect = self.lineView.frame;
                    rect.origin.x = (width - rect.size.width) / 2 + (width * tag);
                    _lineView.frame = rect;
                }];
            }
}

@end
